package gxprod.androidai.support;

import gxprod.androidai.DataCollection;

import java.util.Vector;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.Settings;

/**
 * A bunch of static functions for looking up info about people, this device, etc.
 * @author Josh Maleszewski
 */
public class Lookup {

	public static String[] getLastMessage(Context c) {
		Uri SMSURI = Uri.parse("content://sms/inbox");
		String[] projection = new String[]{"_id", "address", "body", "date"};
		Cursor cursor = null;
		try {
			cursor = c.getContentResolver().query(SMSURI, projection, null, null, null);
			if (cursor != null && cursor.moveToFirst()) {
				return new String[] {
						Integer.toString(cursor.getInt(cursor.getColumnIndex("_id"))),
						cursor.getString(cursor.getColumnIndex("address")),
						cursor.getString(cursor.getColumnIndex("body")),
						cursor.getString(cursor.getColumnIndex("date"))
				};
			}
		} finally {
			if (cursor != null) cursor.close();
		}
		return null;
	}



	public static String getNameFromNumber(Context c, String number) {
		number = number.replaceAll("[\\(\\)\\-\\+]", "");

		ContentResolver localContentResolver = c.getContentResolver();
		Cursor cursor = localContentResolver.query(
				Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)),
				new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID}, null, null, null);


		cursor.moveToFirst();
		if(cursor.getCount() <= 0)
			return number;
		String s  = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
		cursor.close();
		return s;
	}

	public static String lookupNumberFromName(Context context, String name) {

		Cursor people = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, "person_name='" + name + "'", null, null);

		people.moveToFirst();  
		int position = 0;
		String contactId = people.getString(people.getColumnIndex(ContactsContract.Contacts._ID));
		String hasPhone = people.getString(people.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
		if (hasPhone.equalsIgnoreCase("1"))
			hasPhone = "true";
		else
			hasPhone = "false" ;
		if (Boolean.parseBoolean(hasPhone)) {
			Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
			while (phones.moveToNext()) {
				String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				phones.close();
				return phoneNumber;
			}
			phones.close(); 
		}   
		if(hasPhone=="false") {   
			return "" + position;
			//mConname.remove(position);
		} else
			position++;
		return name;
	}

	public static Vector<BasicEntry<String, String>> getNumberNameSetFromName(Context context, String name) {

		String aName= (String)DataCollection.Aliases.get(name.toLowerCase());
		String number = null;
		Vector<BasicEntry<String, String>> matches = new Vector<BasicEntry<String,String>>();

		aName = (String) DataCollection.Aliases.get(name.toLowerCase());

		if(aName != null) {
			number = lookupNumberFromName(context, aName);
			if(number != null){
				matches.add(new BasicEntry<String, String>(aName, number));
				return matches;
			}
		} 

		aName = name;

		String whereName = ContactsContract.Data.MIMETYPE + " = ?";
		String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
		Cursor people = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);   

		people.moveToFirst();

		Vector<String> names = new Vector<String>();
		while(people.moveToNext()){	
			try{
				String cName = people.getString(people.getColumnIndex(PhoneLookup.DISPLAY_NAME));
				names.add(cName);
				if(cName.contains(name)) 
					matches.add(new BasicEntry<String, String>(cName, number));				
			} catch(Exception ex) {
				ex.printStackTrace();
			}
		} 
		people.close();
		return matches;
	}


	public static Vector<BasicEntry<String, String>> lookupIncompleatNamesNumbers(Context context, String person) {

		person = person.toLowerCase();		
		Vector<BasicEntry<String, String>> matches = new Vector<BasicEntry<String, String>>();

		Cursor cursor = context.getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI,
				new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
				null, null, null);
		if(cursor == null) 
			return matches;

		cursor.moveToFirst();		
		while(cursor.moveToNext()) {
			String Name = cursor.getString(cursor.getColumnIndex("display_name"));
			String name = Name.toLowerCase();
			if(name.contains(person) | person.contains(name)) {
				///String hasPhone = cursor.getString(cursor.getColumnIndex("has_phone_number"));
				//if(hasPhone.equals("1")) {
					String number = cursor.getString(cursor.getColumnIndex("number"));
					matches.add(new BasicEntry<String, String>(Name, number));
				//}
			}
		}
		cursor.close();

		return matches;
	}





	/** Get the user friendly name of this device */
	public static String getDeviceFriendlyName(ContentResolver resolver) {
		return Settings.System.getString(resolver, android.os.Build.DEVICE);
	}
	/** Returns the model number of this device */
	public static String getDeviceName(ContentResolver resolver) {
		return Settings.System.getString(resolver, android.os.Build.MODEL);
	}




}
